<template>
  <div class="mod-config">
    <el-card class="box-card search-input" shadow="never">
      <el-form label-width="120px"  size="mini" :model="dataForm">
        <el-row>
          <el-col :span="6">
            <el-form-item label="直播间名称：">
              <el-input v-model="dataForm.title" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="主播姓名：">
              <el-input v-model="dataForm.anchorName" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="主播昵称：">
              <el-input v-model="dataForm.anchorNickName" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开播时间：">
              <el-date-picker
                @change="startTimeChange"
                style="width: 100%"
                v-model="startTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="直播间状态：">
              <cy-select url="/api/v1/broadcast/config/live_status/val" :all-option="true" v-model="dataForm.status"></cy-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建日期：">
              <el-date-picker
                @change="createTimeChange"
                style="width: 100%"
                v-model="createTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="直播间编码：">
              <el-input v-model="dataForm.number" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-form-item>
              <el-button type="primary" @click="$refs.CyTable.query(dataForm)">查询</el-button>
              <el-button @click="reset()">重置</el-button>
              <el-button type="primary" @click="showEdit">创建直播间</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <live-info-table
      url="/api/v1/liveInfo/list"
      :max-height="600"
      :highlightCurrentRow="true"
      :operationWidth="340"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showEditOperation="true"
      :showBatchDelete="false"
      :showSelection="false"
      :showDeleteOperation="true"
      @handleDelete="handleDelete"
      @handleEdit="handleEdit"
      @handleConsole="handleConsole"
      @handleCustom="handleCustom"
      @findPage="findPage"
      @copy="copy"
      @handleLiveData="handleLiveData"
      ref="CyTable"
    >
    </live-info-table>
    <el-dialog
      width="50%"
      :title="operation?'创建直播间':'编辑直播间'"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      @close="editCancel">
      <el-row v-loading="addLoading">
        <el-form label-width="120px" ref="editDataForm" size="mini" :rules="rules" :model="editDataForm">
          <el-col :span="24">
            <el-form-item label="直播标题：" prop="title">
              <el-input v-model="editDataForm.title" maxlength="10" placeholder="最多可编辑10个字" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开播时间：" prop="startTime">
              <el-date-picker
                v-model="editDataForm.startTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                :picker-options="expireTimeOption"
                style="width:100%"
                placeholder="选择开播时间">
              </el-date-picker>
              <div>1）请在{{editDataForm.startTime||'xxxx-xx-xx xx:xx'}}前开播，超时将失效</div>
              <div>2）最长可直播16小时，超时将终止直播</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="广场封面：" prop="squareCover">
              <cy-file-upload
                v-model="editDataForm.squareCover"
                @onSuccess="squareCoverUploadSuccess"
                :before-upload="squareCoverUpload"
              ></cy-file-upload>
              <div>要求封面图尺寸 360px*360px，封面图不允许有文字和图片拼接</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="瀑布流封面：" prop="homeCover">
              <cy-file-upload
                v-model="editDataForm.homeCover"
                @onSuccess="homeCoverUploadSuccess"
                :before-upload="homeCoverUpload"
              ></cy-file-upload>
              <div>要求封面图尺寸 344px*540px，封面图不允许有文字和图片拼接</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主推封面：" prop="mainCover">
              <cy-file-upload
                v-model="editDataForm.mainCover"
                @onSuccess="mainCoverUploadSuccess"
                :before-upload="mainCoverUpload"
              ></cy-file-upload>
              <div>要求封面图尺寸 684px*220px，封面图不允许有文字和图片拼接</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="推广海报：" prop="spreadBill">
              <cy-file-upload
                v-model="editDataForm.spreadBill"
                @onSuccess="spreadBillUploadSuccess"
                :before-upload="spreadBillUpload"
              ></cy-file-upload>
              <div>1）要求封面图尺寸622px*622px</div>
              <div>2）不添加则默认将直播封面作为海报封面</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主播账号：" prop="anchorId">
              <cy-select v-if="dialogVisible" url="/api/v1/liveInfo/anchorList" v-model="editDataForm.anchorId"></cy-select>
            </el-form-item>
          </el-col>
          <!--<el-col :span="24">-->
          <!--<el-form-item label="直播人员：" prop="personInfo">-->
          <!--<el-input v-model="editDataForm.personInfo" clearable></el-input>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="24">
            <el-form-item label="点赞：">
              <el-checkbox :true-label="0" :false-label="1" v-model="editDataForm.isLike">点赞</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="评论：">
              <el-checkbox :true-label="0" :false-label="1" v-model="editDataForm.isComment">评论</el-checkbox>
            </el-form-item>
          </el-col>
          <!--<el-col :span="24">-->
          <!--<el-form-item label="回放：">-->
          <!--<el-checkbox :true-label="0" :false-label="1" v-model="editDataForm.isPlayback">回放</el-checkbox>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="24">
            <el-form-item label="备注：" prop="remark">
              <el-input  maxlength="255" placeholder="最多可编辑255个字" v-model="editDataForm.remark" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: center;">
            <el-button size="small" type="primary" @click="dataFormSubmit('save')">保存</el-button>
            <el-button size="small" type="success" style="margin-left: 20px" @click="dataFormSubmit('release')">发布</el-button>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
    <el-dialog
      title=""
      :visible.sync="releaseVisible"
      width="30%"
      center>
      <el-row style="text-align: center;">
        <el-col>
          <i class="el-icon-success" style="font-size: 80px;color: #000000"></i>
        </el-col>
        <el-col style="margin-top: 20px">
          <el-button style="width: 50%" @click="openConsole">去添加商品</el-button>
        </el-col>
        <el-col style="margin-top: 20px">
          <el-button style="width: 50%" @click="openConsole">去添加互动</el-button>
        </el-col>
        <!--<el-col style="margin-top: 20px">-->
        <!--<el-button style="width: 50%" @click="openLiveCode">查看开播码</el-button>-->
        <!--</el-col>-->
      </el-row>
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" size="small" @click="releaseVisible = false">完 成</el-button>
          </span>
    </el-dialog>


    <el-dialog
      width="94%"
      title="直播间控制台"
      :close-on-click-modal="false"
      :visible.sync="dialogConsoleVisible"
      @close="consoleCancel">
      <live-controller :data="consoleLineData" ref="liveController"></live-controller>
    </el-dialog>

    <el-dialog
      width="90%"
      title="直播数据"
      :close-on-click-modal="false"
      :visible.sync="dialogLiveDataVisible"
      @opened="opened"
      @closed="closed">
      <el-tabs v-model="liveDataTab" @tab-click="liveDataClick">
        <el-tab-pane label="基础数据" name="basis">
          <live-info-data-basis ref="dataBasis" :formData="currentRow"></live-info-data-basis>
        </el-tab-pane>
        <el-tab-pane label="商品数据"  name="shop">
          <live-info-data-shop ref="dataShop"></live-info-data-shop>
        </el-tab-pane>
        <el-tab-pane label="抽奖数据" name="lottery">
          <live-info-data-lottery ref="dataLuck"></live-info-data-lottery>
        </el-tab-pane>
        <el-tab-pane label="领券数据" name="coupon">
          <live-info-data-coupon ref="dataCoupon"></live-info-data-coupon>
        </el-tab-pane>
        <el-tab-pane label="直播数据" name="live" >
          <live-info-data-live ref="dataLive"> </live-info-data-live>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog
      title="开播码"
      :visible.sync="codeDialogVisible"
      width="30%"
      center
      append-to-body>
      <div style="text-align: center;">
        <img width="240" height="240" src="https://static4.laiyifen.com/ztdev-files/broadcast-admin-web/image/1594023656777_3424.png">
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import CySelect from "./component/CySelect";
  import CyFileUpload from "./component/CyFileUpload";
  import LiveInfoTable from "./liveinfoComponent/LiveInfoTable";
  import LiveInfoDataBasis from "./liveinfoComponent/LiveInfoDataBasis";
  import LiveInfoDataCoupon from "./liveinfoComponent/LiveInfoDataCoupon";
  import LiveInfoDataLive from "./liveinfoComponent/LiveInfoDataLive";
  import LiveInfoDataLottery from "./liveinfoComponent/LiveInfoDataLottery";
  import LiveInfoDataShop from "./liveinfoComponent/LiveInfoDataShop";
  import LiveController from "./liveinfoComponent/LiveController";
  export default {
    components: {
      CySelect,
      CyFileUpload,
      LiveInfoTable,
      LiveInfoDataBasis,
      LiveInfoDataCoupon,
      LiveInfoDataLive,
      LiveInfoDataLottery,
      LiveInfoDataShop,
      LiveController,
    },
    data() {
      return {
        shopStatus:0,
        codeDialogVisible: false,
        loading: false,
        addLoading: false,
        moreBtnDisable: true,
        liveInfoStatus: [{
          value: 15,
          label: '待直播'
        }, {
          value: 16,
          label: '直播中'
        }, {
          value: 17,
          label: '违规下线'
        }, {
          value: 18,
          label: '已结束'
        }, {
          value: 19,
          label: '编辑中'
        }],
        createTime: [],
        startTime: [],
        dataForm: {},
        editDataForm: {
          squareCover:'',
          homeCover:'',
          mainCover:'',
          spreadBill:''
        },
        expireTimeOption:{
          disabledDate(date) {
            let time = date.getTime();
            return  time<= Date.now() - 24*60*60*1000 || time >= Date.now() + 14*24*60*60*1000;
          }
        },
        imageAddBtn:{
          width: '180px',
          height: '120px',
          marginBottom: '10px'
        },
        columns: [],
        filterColumns: [],
        bannerList:[],
        totalSize: 0,
        operation: true, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        releaseVisible: false,
        dialogConsoleVisible: false, //直播控制台页面
        consoleLineData: null, // 直播控制选中行数据
        dialogLiveDataVisible: false, //直播数据页面
        liveDataTab: 'basis', //直播数据页面
        editLoading: false,
        countNumForm: {
          allShopNum: '',
          onlineNum: '',
          offlineNum: ''
        },
        dataListSelections: [],
        invoiceUpdateVisible: true,
        currentRow:null,
        saveObjectId:0,// 保存返回的ID
        rules: {
          title: [
            { required: true, message: '请填写直播间标题', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '请选择开播时间', trigger: 'blur' },
            {validator:(rule, value, callback)=>{
                let date = value.replace(/-/g,'/');
                let timestamp = new Date(date).getTime();
                let currentTimestamp = new Date().getTime();
                if(timestamp<currentTimestamp){
                  callback(new Error('开播时间不能小于当前时间'));
                } else {
                  callback();
                }
              },trigger: 'blur'}
          ],
          homeCover: [
            { required: true, message: '请选择首页封面', trigger: 'blur' }
          ],
          squareCover: [
            { required: true, message: '请选择广场封面', trigger: 'blur' }
          ],
          anchorId: [
            { required: true, message: '请选择主播账号'},
            {validator:this.verifyAnchor,}
          ],
          personInfo: [
            { required: true, message: '请填写主播昵称', trigger: 'blur' }
          ]
        },
      }
    },
    mounted: function () {
      this.columns = [
        {prop: "number", label: "直播间编码", minWidth: 120},
        {prop: "homeCover", label: "直播封面图", minWidth: 130, showType:'image',imgSize:{width:100,height:100}},
        {prop: "title", label: "直播间名称", minWidth: 120},
        {prop: "anchorName", label: "主播姓名", minWidth: 120},
        {prop: "anchorNickName", label: "主播昵称", minWidth: 120},
        {prop: "startTime", label: "开播时间", minWidth: 180},
        {prop: "actualStartTime", label: "实际开播时间", minWidth: 180},
        {prop: "actualEndTime", label: "结束时间", minWidth: 180},
        {prop: "createTime", label: "创建日期", minWidth: 180},
        {prop: "statusValue", label: "状态", minWidth: 120},
        {prop: "remark", label: "备注", minWidth: 120},
      ];
      let temp = [];
      this.columns.forEach(function (key, val) {
        temp.push(key);
      });
      this.filterColumns = temp;
      this.init();
    },
    methods: {
      init(){
        this.utils.request.liveRequest({
          url: '/api/v1/broadcast/shopInfo/isBanShopInfo',
          method: 'get',
        }).then(result => {
          let data = result.data;
          if (data.data!=null) {
            this.shopStatus=data.data;
          }
        })
      },
      findPage(){
        this.$refs.CyTable.findPage(this.dataForm);
      },
      //重置
      reset() {
        this.createTime = []
        this.startTime = []
        this.dataForm = {};
        this.$refs.CyTable.resetForm(this.dataForm);
      },
      verifyAnchor(rule, value, callback){
        if(value==null || value== undefined){
          return;
        }
        let param={'anchorId':value}
        this.utils.request.liveRequest({
          url: '/api/v1/liveInfo/livingInfoByAnchor',
          method: 'get',
          params: param
        }).then(result => {
          let data = result.data;
          if (data.data==1) {
            callback(new Error('当前主播已经被删除'));
          }else if (data.data==2) {
            callback(new Error('当前主播禁播中'));
          }  else if(data.data==3){
            callback(new Error('当前主播正在直播中'));
          }else{
            callback();
          }
        })
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
        if (this.dataListSelections.length > 0) {
          this.moreBtnDisable = false
        } else {
          this.moreBtnDisable = true
        }
      },
      // 显示编辑界面
      handleEdit: function (params) {
        this.showEdit();
        this.operation = false;
        let param = {
          number: params.row.number
        }
        let this_ = this
        this.utils.request.liveRequest({
          url: '/api/v1/liveInfo/detail',
          method: 'get',
          params: param
        }).then(result => {
          let data = result.data
          this_.editDataForm = data.data
          this_.$nextTick(() => {
            if (this_.$refs['editDataForm'] !== undefined) {
              this_.$refs['editDataForm'].clearValidate();
            }
          });
        })
      },
      showEdit(){
        if(this.shopStatus==2){
          this.$message({message: "您已经被禁播", type: "error"});
          return;
        }
        this.operation = true;
        this.dialogVisible = true;
      },
      // 删除
      handleDelete: function (params) {
        let ids = params.params;
        let delDataForm = {
          id:ids[0].id
        };
        let this_ = this;
        this.utils.request.liveRequest({
          url: '/api/v1/liveInfo/delete',
          method: 'get',
          params: delDataForm
        }).then(result => {
          let data = result.data;
          if (data.code === '0') {
            this_.$refs.CyTable.findPage(this_.dataForm)
            this_.$forceUpdate();
          } else {
            this.$message({message: "删除失败", type: "error"});
          }
        })
      },
      // 显示自定义界面
      handleCustom: function (params) {
        this.dialogVisible = true;
        this.operation = false;
        this.dataForm = Object.assign({}, params.row);
        this.$nextTick(() => {
          if (this.$refs['dataForm'] !== undefined) {
            this.$refs['dataForm'].clearValidate();
          }
        });
      },
      // 显示控制台页面
      handleConsole: function (params) {
        this.consoleLineData = params.row
        this.dialogConsoleVisible = true;
      },
      openLiveCode: function(){
        // 查询详情
        this.codeDialogVisible = true;
      },
      openConsole: function () {
        // 查询详情
        this.utils.request.liveRequest({
          url: '/api/v1/liveInfo/detail/'+this.saveObjectId,
          method: 'get'
        }).then(result => {
          let data = result.data
          if(data.code=='0'){
            this.consoleLineData = data.data
            this.dialogConsoleVisible = true;
          }
        })
      },
      copy(row){
        this.showEdit();
        let param = {
          number: row.number
        }
        this.utils.request.liveRequest({
          url: '/api/v1/liveInfo/detail',
          method: 'get',
          params: param
        }).then(result => {
          let data = result.data
          this.editDataForm = data.data
          this.editDataForm.startTime = ''
        })
      },
      // 创建日期改变
      createTimeChange: function (val) {
        if (val) {
          this.dataForm.createTimeStart = val[0]
          this.dataForm.createTimeEnd = val[1]
        } else {
          this.dataForm.createTimeStart = ''
          this.dataForm.createTimeEnd = ''
        }
      },
      // 开播时间改变
      startTimeChange: function (val) {
        if (val) {
          this.dataForm.startTimeStart = val[0]
          this.dataForm.startTimeEnd = val[1]
        } else {
          this.dataForm.startTimeStart = ''
          this.dataForm.startTimeEnd = ''
        }
      },
      // 编辑取消
      editCancel(){
        this.dialogVisible = false
        this.editDataForm = {
          homeCover:'',
          mainCover:'',
          squareCover:'',
          spreadBill:''
        }
      },
      // 直播控制台关闭回调
      consoleCancel(){
        this.consoleLineData = null
      },
      // 新增提交
      dataFormSubmit(type){
        if(type=='save'){
          this.editDataForm.status=19;
        }else if(type=='release'){
          this.editDataForm.status=15;
        }
        let url;
        if(this.operation){
          url='save'
        } else {
          url = 'update'
          this.saveObjectId=this.editDataForm.id;
        }
        let this_ = this;
        this.$refs['editDataForm'].validate((valid) => {
          if (valid) {
            this.$confirm("确认操作吗？", "提示", {}).then(() => {
              this_.addLoading=true;
              this.utils.request.liveRequest({
                url: '/api/v1/liveInfo/' + url,
                method: 'Post',
                params: this.editDataForm
              }).then(result => {
                let data = result.data;
                if (data.code === '0') {
                  this.saveObjectId = data.data;
                  //如果是修改状态，直接赋值
                  if(!this.operation){
                    this.saveObjectId=this.editDataForm.id;
                  }
                  this_.editCancel();
                  this_.$refs.CyTable.findPage(this_.dataForm)
                  this_.$forceUpdate();
                  if (type == 'save') {
                    this_.$message({message: "直播间保存成功", type: "success"});
                  } else if (type == 'release') {
                    this_.releaseVisible = true
                  }
                } else {
                  this.$message.error(data.msg)
                }
                this_.addLoading=false;
              })
            })
          } else {
            return false;
          }
        });
      },
      squareCoverUploadSuccess(res, file) {
        this.editDataForm.squareCover = res.data;
      },
      homeCoverUploadSuccess(res, file) {
        this.editDataForm.homeCover = res.data;
      },
      mainCoverUploadSuccess(res, file) {
        this.editDataForm.mainCover = res.data;
      },
      spreadBillUploadSuccess(res, file) {
        this.editDataForm.spreadBill = res.data;
      },
      handleLiveData(row){
        this.dialogLiveDataVisible = true
        this.currentRow = row
      },
      opened(){
        // 基础数据初始化
        //this.$refs.dataBasis.init(this.currentRow);
      },
      closed(){
        this.liveDataTab = 'basis'
      },
      liveDataClick(tab, event){
        // this.$nextTick(function () {
        if(this.liveDataTab === 'basis'){
          console.log('基础数据')
        } else if(this.liveDataTab === 'shop'){

          this.$refs.dataShop.getPData(this.currentRow);
          console.log('商品数据')
        } else if(this.liveDataTab === 'lottery'){
          this.$refs.dataLuck.getPData(this.currentRow);
          console.log('抽奖数据')
        } else if(this.liveDataTab === 'coupon'){
          this.$refs.dataCoupon.getPData(this.currentRow);
          console.log('领券数据')
        } else if(this.liveDataTab === 'live'){
          this.$refs.dataLive.getPData(this.currentRow);
          console.log('直播数据')
        }
        // })

      },
      //瀑布流封面
      homeCoverUpload(file){
        return this.beforeAvatarUpload(file,'344','540')
      },
      //直播广场封面
      squareCoverUpload(file){
        return this.beforeAvatarUpload(file,'360','360')
      },
      //主推封面
      mainCoverUpload(file){
        return this.beforeAvatarUpload(file,'684','220')
      },
      //推广海报
      spreadBillUpload(file){
        return this.beforeAvatarUpload(file,'622','622')
      },
      //子组件上传验证
      beforeAvatarUpload(file, width ,height) {
        // 限制图片大小
        const isSize = new Promise((resolve,reject)=> {
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.src = _URL.createObjectURL(file)
          img.onload = function() {
            let valid = img.width == width && img.height == height
            valid ? resolve() : reject();
          }
        })
          .then(()=>{
            return file;
          },()=>{
            this.$message.error('上传图片像素格式为'+width+'*'+height+'!');
            return Promise.reject();
          })
        return isSize;
      }
    }
  }
</script>
<style lang="scss">
  #app{
    text-align: left;
  }
</style>
